package com.itheima.controller.store.company;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.BaseServlet;
import com.itheima.domain.Company;
import com.itheima.utils.BeanUtil;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/store/company/*")
public class CompanyServlet extends BaseServlet {

    /**
     * 查询全部公司用户
     * @param req
     * @param resp
     * @throws IOException
     */
    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取当前页码和每页条目数
        String page = req.getParameter("page");
        String pageSize = req.getParameter("pageSize");
        // 调用业务层方法
        List<Company> companyList = companyService.findAll(page, pageSize);
        // 将分页相关参数封装
        PageInfo<Company> pageInfo = new PageInfo<>(companyList);
        // 存入会话域
        req.getSession().setAttribute("page", pageInfo);
        // 请求转发
        try {
            req.getRequestDispatcher("/pages/store/company/list.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private void save(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        Company company = BeanUtil.fillBean(req, Company.class,"yyyy-MM-dd");
        companyService.save(company);
        findAll(req,resp);
    }

    private void findById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");

   Company company=companyService.findById(id);

   req.getSession().setAttribute("company",company);

        try {
            req.getRequestDispatcher("/pages/store/company/update.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        }

    }


    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        Company company = BeanUtil.fillBean(req, Company.class);

        companyService.update(company);

        findAll(req,resp);


    }


    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String ids = req.getParameter("id");
        companyService.delete(ids);
        findAll(req,resp);
    }


}
